//
//  EWReservationViewController.m
//  haveSomethingToEat
//
//  Created by 陈 宁权 on 17/6/9.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "EWReservationViewController.h"
#import "EWSectionHeaderView.h"
#import "EWBusinessInfo.h"
#import "EWBusinessInfoCell.h"
#import "EWAddBusinessCell.h"
#import "EWShoppingCartController.h"
#import "EWAddBusinessController.h"

@interface EWReservationViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *BusinessArr;
@property (nonatomic,strong) NSMutableArray *collectionBusinessArr;
@property (nonatomic,strong) NSMutableArray *recommendBusinessArr;
@end

@implementation EWReservationViewController

- (NSMutableArray *)BusinessArr
{
    if (!_BusinessArr) {
        _BusinessArr = [NSMutableArray array];
    }
    return _BusinessArr;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor grayColor];
    //配置导航栏
    [self configNav];
    //配置tableView
    [self configTableView];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
}

- (void)configNav
{
    [self.navigationItem setTitle:@"订餐"];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, 17, 17);
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
}

- (void)configTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.tableView.sectionHeaderHeight = 0.0;
    self.tableView.sectionFooterHeight = 0.0;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,0.001)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

- (void)headerRefresh
{
    //加载商家数据
    [[BQUserDao shareObject] getBusinessInfoListandServiceReceiveResponseSuccess:^(id response) {
        //字典数组转模型数组
        _BusinessArr = [EWBusinessInfo mj_objectArrayWithKeyValuesArray:response[@"businessInfos"]];
        _collectionBusinessArr = [NSMutableArray array];
        _recommendBusinessArr = [NSMutableArray array];
        for (EWBusinessInfo *businessInfo in _BusinessArr) {
            if ([businessInfo.creatorId isEqualToString:[RCIM sharedRCIM].currentUserInfo.userId]) {
                [_collectionBusinessArr addObject:businessInfo];
            }
            else
            {
                [_recommendBusinessArr addObject:businessInfo];
            }
            
        }
        [_collectionBusinessArr addObject:@"addBusinessCell"];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } ServiceReceiveResponseFailed:^(id response) {
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD showErrorWithStatus:response];
    }];
}

//点击搜索按钮
- (void)searchBtnClick
{
    NSLog(@"点击了搜索按钮");
}

#pragma mark UItTbleview代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return _collectionBusinessArr.count;
    }
    else
    {
        return _recommendBusinessArr.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_collectionBusinessArr.count < 1 && _recommendBusinessArr.count < 1) {
        return [UIView new];
    }
    else{
        EWSectionHeaderView *sectionView = [EWSectionHeaderView cellWithTableView:self.tableView];
        if (section == 0) {
            sectionView.title = @"——— 自添加商家 ———";
        }
        else if (section == 1)
        {
            sectionView.title = @"——— 推荐商家 ———";
        }
        return sectionView;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {//收藏商家
        if ([_collectionBusinessArr[indexPath.row] isKindOfClass:[NSString class]]) {
            EWAddBusinessCell *addBusinessCell = [EWAddBusinessCell cellWithTableView:tableView];
            addBusinessCell.selectionStyle = UITableViewCellSelectionStyleNone;
            return addBusinessCell;
        }
        else{
            EWBusinessInfoCell *collectionBusiness = [EWBusinessInfoCell cellWithTableView:tableView];
            collectionBusiness.businessInfo = _collectionBusinessArr[indexPath.row];
            collectionBusiness.selectionStyle = UITableViewCellSelectionStyleNone;
            return collectionBusiness;
        }
    }
    else//推荐商家
    {
        EWBusinessInfoCell *recommendBusiness = [EWBusinessInfoCell cellWithTableView:tableView];
        recommendBusiness.businessInfo = _recommendBusinessArr[indexPath.row];
        recommendBusiness.selectionStyle = UITableViewCellSelectionStyleNone;
        return recommendBusiness;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == _collectionBusinessArr.count - 1) {//添加商家
        EWAddBusinessController *addBusinessVC = [[EWAddBusinessController alloc] init];
        EWBaseNavViewController *addBusinessNav = [[EWBaseNavViewController alloc] initWithRootViewController:addBusinessVC];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.view.window.rootViewController presentViewController:addBusinessNav animated:YES completion:nil];
        });
    }
    else{
        __weak typeof(self) weakself = self;
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"请选择订餐方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *randomMenu = [UIAlertAction actionWithTitle:@"由系统随机菜单" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        UIAlertAction *chooseByself = [UIAlertAction actionWithTitle:@"自己选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            EWShoppingCartController *shoppingVC = [[EWShoppingCartController alloc] init];
            if (indexPath.section == 0) {
                shoppingVC.business = self.collectionBusinessArr[indexPath.row];
            }
            else{
                shoppingVC.business = self.recommendBusinessArr[indexPath.row];
            }
//            EWBaseNavViewController *shoppingNav = [[EWBaseNavViewController alloc] initWithRootViewController:shoppingVC];
//            [weakself.view.window.rootViewController presentViewController:shoppingNav animated:YES completion:nil];
            [weakself.navigationController pushViewController:shoppingVC animated:YES];
            
        }];
        
        UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:randomMenu];
        
        [alertController addAction:chooseByself];
        
        [alertController addAction:cancelAction];
        
        if ([UIDevice.currentDevice.model isEqualToString:@"iPad"]) {
            UIPopoverPresentationController *popover = alertController.popoverPresentationController;
            
            if (popover) {
                popover.sourceView = self.view;
                popover.sourceRect = self.view.bounds;
                popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself presentViewController:alertController animated:YES completion:nil];
        });
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == _collectionBusinessArr.count - 1) {
        return 65;
    }
    return 70;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
